<?php
/**
 *	  [Jsen.net] (C)2013-2099 Jason Group Science and technology co., LTD.
 *	  This is NOT a freeware, use is subject to license terms
 *
 *	  http://www.jsen.net
 *	  tel:400-681-9511
 */
class AdminMoneyLogController extends AdminBaseController {
	/**
	 * 自动执行
	 */
	public function _initialize() {
		parent::_initialize(); 
		$this->db = model('user_moneylog');
	}

	/**
	 * 会员财务管理
	 */   
	public function index() {
		//excel导出
		// if($_GET["act"]=="excel"){
		// 	$sqlmap = array();
		// 	if ($_GET['keyword']) {
		// 		$map = array();
		// 		$map['username'] = array('LIKE',"%".trim($_GET['keyword'])."%");
		// 		$ids = model('user')->where($map)->getField('id',TRUE);
		// 		$sqlmap['u.id'] = array('in',$ids);
		// 	}
		// 	if($_GET["start"]!="" or $_GET["end"]!=""){
		// 			$start = strtotime($_GET['start'].' 00:00:00');
		// 			$end = strtotime($_GET['end'].' 23:59:59');
		// 			$sqlmap['add_time'] =array('between',[date('Y-m-d H:i:s',$start),date('Y-m-d H:i:s',$end)]);
		// 	}
		// 	if($_GET["type"]!==""){
		// 		$sqlmap['if_reward'] = array('eq',$_GET["type"]);
		// 	}
		// 	$_GET['pagenum'] = isset($_GET['page']) ? intval($_GET['page']) : 1;
		// 	$_GET['rowsnum'] = isset($_GET['rows']) && (int)($_GET['rows']) != 0 ? intval($_GET['rows']) : PAGE_SIZE;
		// 	$headerArr = array(
		// 		'username'=>'会员名',
		// 		'real_name'=>'真实姓名',
		// 		'balance'=>'GF投注金额',
		// 		'beans'=>'获得豆',
		// 		'reward_prize'=>'中奖金额',
		// 		'if_reward'=>'状态',
		// 		'add_time'=>'时间',
		// 	);
		// 	$list = M('upvaluation_put_records')->field(true)->where($sqlmap)->order("id desc");
		// 	$this->DownloadCSV($list, $headerArr);
		// 	exit;
		// }
		if (IS_POST) {
			$is_cache=true;
			$sqlmap = array();
			if ($_GET['keyword']) {
				$map = array();
				$map['username|real_name'] = array('LIKE',"%".trim($_GET['keyword'])."%");
				$ids = model('user')->where($map)->getField('id',TRUE);
				
				$sqlmap['u.id'] = array('in',$ids);
				$is_cache=false;
			}
			
			if($_GET["start"]!="" or $_GET["end"]!=""){
					$start = strtotime($_GET['start'].' 00:00:00');
					$end = strtotime($_GET['end'].' 23:59:59');
					$sqlmap['up.add_time'] =array('between',[date('Y-m-d H:i:s',$start),date('Y-m-d H:i:s',$end)]);
					$is_cache=false;
			}
			
			if($_GET['if_reward']){
				$sqlmap['up.if_reward'] = $_GET['if_reward'];
			}

			$_GET['pagenum'] = isset($_GET['page']) ? intval($_GET['page']) : 1;
			$_GET['rowsnum'] = isset($_GET['rows']) && (int)($_GET['rows']) != 0 ? intval($_GET['rows']) : PAGE_SIZE;
			$data = array();
			$result = M('upvaluation_put_records up')
					->where($sqlmap)
					->join('__USER__ u on up.user_id=u.id')
					->field('u.username,u.real_name,up.*')
					->limit(($_GET['pagenum']-1)*$_GET['rowsnum'].','.$_GET['rowsnum'])
					->order('up.id desc')
					->select();
			$result = is_array($result) ? $result : array();
			$data_sum = M('upvaluation_put_records')->field("count(id) as total,sum(balance) as money,sum(reward_prize) as reward_prize")->find();
			$data['total']=$data_sum["total"];
			$data['money']=$data_sum["money"];
			$data['user_money']=$data_sum["reward_prize"];
			$data['title']="统计概览 -累计投注金额：" . ($data["money"] == "" ? "0.00" : $data["money"]) . "元&nbsp;&nbsp;累计中奖金额：" . ($data["user_money"] == "" ? "0.00" : $data["user_money"]) . "元&nbsp;&nbsp;";
			// if($is_cache==true){
			// 	$data_sum=S("admin_money_log");
			// 	if($data_sum==""){
			// 		$data_sum =  M('upvaluation_put_records')->cache('admin_money_log',1800)->field("count(id) as total,sum(balance) as money,sum(reward_prize) as reward_prize")->where($sqlmap)->find();	
			// 		// var_dump($data_sum);
			// 		S('last_log_time',date("Y-m-d H:i:s"),1800);
			// 		$data_sum=S("admin_money_log");
			// 	}
			// 	$data['total']=$data_sum[0]["total"];
			// 	$data['money']=$data_sum[0]["money"];
			// 	$data['user_money']=$data_sum[0]["reward_prize"];
			// 	$data['title']="统计概览（30分钟更新一次,上次更新时间".S('last_log_time')."）-累计投注金额：" . ($data["money"] == "" ? "0.00" : $data["money"]) . "元&nbsp;&nbsp;累计中奖金额：" . ($data["user_money"] == "" ? "0.00" : $data["user_money"]) . "元&nbsp;&nbsp;";
			// }else{
			// 	$data_sum = M('upvaluation_put_records')->field("count(id) as total,sum(balance) as money,sum(reward_prize) as reward_prize")->where($sqlmap)->find();
			// 	// var_dump($data_sum);
			// 	$data['total']=$data_sum["total"];
			// 	$data['money']=$data_sum["money"];
			// 	$data['user_money']=$data_sum["reward_prize"];
			// 	$data['title']="统计概览 -累计投注金额：" . ($data["money"] == "" ? "0.00" : $data["money"]) . "元&nbsp;&nbsp;累计中奖金额：" . ($data["user_money"] == "" ? "0.00" : $data["user_money"]) . "元&nbsp;&nbsp;";
			// }
			$data['if_reward'] = array(
				array(
					'id'=>1,
					'name'=>'未中奖'
				),
				array(
					'id'=>2,
					'name'=>'中奖'
				),
				array(
					'id'=>3,
					'name'=>'后台操作中奖'
				),
			);

			foreach($data['if_reward'] as $key => $value){
				if($value['id'] == $_GET['if_reward']) $data['if_reward'][$key]['selected'] = true;
			}
			$data['rows'] = $result;
			echo json_encode($data);
		}else {
			include $this->admin_tpl('admin_money_log');
		}
	}
	//GF投注记录+中奖记录 -> 后台添加中奖记录
	public function add_record()
	{
		if(IS_POST){
			//reward_prize
			$data['reward_prize'] = $_POST['reward_prize'];
			$data['id'] = $_POST['id'];
			if(!$data['reward_prize'] || !is_numeric($data['reward_prize'])){
				showmessage('请填写合法的数字格式');
			}
			$data['if_reward'] = 2;
			$data['add_time'] = date('Y-m-d H:i:s');
			try{
				M('upvaluation_put_records')->where(array('id'=>$data['id']))->save($data);
				C('site_jackpot_percent',0);
			}catch(\Exception $e){
				showmessage($e->getMessage());
			}
			showmessage('操作成功');
		}else{
			showmessage('非法访问');
		}
	}
	
	//增加奖池金额
	public function add_jackpot()
	{	
		$file = $this->_post('files');//site.php
		if(IS_POST){
			unset($_POST['files']);
			$add = trim($_POST['add']);
			if(!$add || !is_numeric($add)){
				showmessage('请填写合法的数字格式');
			}
		
			$value = C('site_jackpot') + $add;
			unset($_POST['add']);
			unset($_POST['site_jackpot']);
			$_POST['site_jackpot'] = $value;
			$site_key =  C('site_key') ;
			$site_key = isset($site_key) ? $site_key : generate_password();
			$_POST['site_key'] = $site_key;
			
			if (file_exists(CONF_PATH . $file)){
				if ($this->update_config(daddslashes($_POST), CONF_PATH . $file)) {
					showmessage('操作成功', '', -1);
				} else {
				  showmessage('操作失败');
				}	
			}else{
				$conf_file=file_put_contents(CONF_PATH . $file, '<?php return array(); ?>');
				if ($this->update_config(daddslashes($_POST), CONF_PATH . $file)) {
					showmessage('操作成功', '', -1);
				} else {
				  showmessage('操作失败');
				}	
			}
			// $this->update_config('site_jackpot',$value) ? showmessage('操作成功') : showmessage('操作失败');
		}else{
			showmessage('非法访问');
		}
	}

	//分红奖列表
	public function fenhong()
	{	
		if (IS_POST) {
			$sqlmap = array();
			if ($_GET['keyword']){
				$map = array();
				$map['username|real_name'] = array('LIKE',"%".trim($_GET['keyword'])."%");
				$ids = model('user')->where($map)->getField('id',TRUE);
				$sqlmap['u.id'] = array('in',$ids);

			}
			
			if($_GET["start"]!="" or $_GET["end"]!=""){
					$start = strtotime($_GET['start'].' 00:00:00');
					$end = strtotime($_GET['end'].' 23:59:59');
					$sqlmap['f.add_time'] =array('between',[date('Y-m-d H:i:s',$start),date('Y-m-d H:i:s',$end)]);
					$is_cache=false;
			}
			if(isset($_GET['type']) && $_GET['type'] != ''){
				$sqlmap['f.type'] = $_GET['type'];
			}
			$_GET['pagenum'] = isset($_GET['page']) ? intval($_GET['page']) : 1;
			$_GET['rowsnum'] = isset($_GET['rows']) && (int)($_GET['rows']) != 0 ? intval($_GET['rows']) : PAGE_SIZE;
			$data = array();
			$data['type'] = array(
				array(
					'id'=>1,
					'name'=>'分红奖'
				),
				array(
					'id'=>2,
					'name'=>'邀请奖'
				),
			);
			foreach($data['type'] as $key => $value){
				if($value['id'] == $_GET['type']) $data['type'][$key]['selected'] = true;
			}
			$result = M('fenhong_records f')
					->join('__USER__ u on u.id=f.user_id')
					->where($sqlmap)
					->field('u.real_name,f.*')
					->limit(($_GET['pagenum']-1)*$_GET['rowsnum'].','.$_GET['rowsnum'])
					->order('f.id desc')
					->select();
			$result = is_array($result) ? $result : array();
			$data['rows'] = $result;
			
			$data['total'] = M('system_config')->where(['id'=>2])->getField('value');
			$data['title']="统计概览--团队累计升值链：" . ($data["total"] == "" ? "0.00" : $data["total"]);
			echo json_encode($data);
		}else {
			include $this->admin_tpl('fenhong');
		}
	}


	private function DownloadCSV($selectObject,$head){
		$fileName=time();
		if ( !is_object( $selectObject ) || !is_array( $head ) ) {
			exit('参数错误!');
		}
		set_time_limit(0);//设置脚本最大执行时间 0=没有限制
		//下载头.
		header ('Content-Type: application/vnd.ms-excel;charset=gbk');
		header ('Content-Disposition: attachment;filename="'.$fileName.'.csv"');
		header ('Cache-Control: max-age=0');
		//输出流;
		$file = 'php://output';
		$fp = fopen ( $file, 'a' );

		function changCode( $changArr ) {
			// 破Excel2003中文只支持GBK编码;
			foreach ( $changArr as $k => $v ) {
				$changArr [$k] = iconv ( 'utf-8', 'gbk', $v );
			}
			//返回一个 索引数组;
			return array_values( $changArr );
		};
		//写入头部;
		fputcsv ( $fp, changCode( $head ) );

		//写入数据;
		$pageSize = 100;//每次查询一百条;
		$page  = 1;//起始页码;
		$list = array();
		//查库;
		$money_type=C("MONEY_TYPE");
		$cloneObj = clone $selectObject;//因为thinkphp内部执行完select方法后会清空对象属性,所以clone;
		while ( $list = $cloneObj ->limit( $pageSize*( ($page++)-1 ), $pageSize )->select()  ) {
			$cloneObj = clone $selectObject;
			//对查询结果二次处理
			foreach ( $list as $key => $value ) {
				$value['add_time']= date('Y-m-d H:i',$value['add_time']); 
				$value['username'] = get_nickname($value['user_id']);
				$value['type'] = $money_type[$value["type"]] == 0 ? '未中奖' : ($money_type[$value["type"]] == 1 ? '中奖' : '后台操作中奖');
				$value = array_intersect_key( $value, $head );//返回需要写入CSV的数据;
				$value = array_merge( $head, $value );//利用此函数返回需要的顺序;
				$value = changCode( $value );
				fputcsv ( $fp, $value );//写入数据;
				flush();
			}
			ob_flush();
		}
		exit();
	}

	/* 财务设置 */
	public function admin_money_log_set() {
		$file = $_POST['files'];
		if(IS_POST) {
			unset($_POST['files']);
			//生成密钥
			$site_key =  C('site_key') ;
			$site_key = isset($site_key) ? $site_key : generate_password();
			$_POST['site_key'] = $site_key;
            if (file_exists(CONF_PATH . $file)){
				if ($this->update_config(daddslashes($_POST), CONF_PATH . $file)) {
					showmessage('操作成功', '', -1);
				} else {
					showmessage('操作失败');
				}	
			}else{
				$conf_file=file_put_contents(CONF_PATH . $file, '<?php return array(); ?>');
				if ($this->update_config(daddslashes($_POST), CONF_PATH . $file)) {
					showmessage('操作成功', '', -1);
				} else {
					showmessage('操作失败');
				}	
			}		
		} else {
			showmessage('请勿非法访问');
		}
	}

	/* 保存配置文件 */
	private function update_config($config, $config_file = '') {
        if(empty($config_file)) return false;
        if($fp = @fopen($config_file, 'wb')) {
            fwrite($fp, "<?php \nreturn " . stripslashes(var_export($config, true)) . ";");
            fclose($fp);
            return true;
        } else {
            return false;
        }
    }

}